package com.iretailer.report.quartz.sendReqularly.protocol;

import com.alibaba.fastjson.JSON;
import com.iretailer.report.model.SendRegularly;
import com.iretailer.report.quartz.sendReqularly.model.FlowArray;
import com.iretailer.report.quartz.sendReqularly.model.ServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Auther: xjw
 * @Date: 2019/8/1 0001 10:22
 * @Description:
 */
public class HttpProtocol {
    private static final Logger log = LoggerFactory.getLogger(HttpProtocol.class);

    public static boolean initAndSend(SendRegularly s, ServerConfig config, List<FlowArray> message) {
        return http(config.getHost(), config.getPort(), config.getPath(), JSON.toJSONString(message));
    }

    public static boolean http(String host, int port, String path, String message) {
        String url = String.format("http://%s:%d/%s", host, port, path);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        HttpEntity<String> formEntity = new HttpEntity<String>(message, headers);
        ResponseEntity response = CreatTestTemplate.getRestTemplate().postForEntity(url, formEntity, String.class);
        if (response.getStatusCodeValue() == 200) {
            return true;
        } else {
            return false;
        }
    }

    private static class CreatTestTemplate {

        private static RestTemplate restTemplate;

        private static synchronized RestTemplate getRestTemplate() {
            if (restTemplate == null) {
                SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
                requestFactory.setConnectTimeout(1000);// 设置超时
                requestFactory.setReadTimeout(1000);
                restTemplate = new RestTemplate(requestFactory);
                return restTemplate;
            } else {
                return restTemplate;
            }
        }
    }
}
